<template>
  <div class="user-list">
    <!-- 查询区域 -->
     <el-form :inline="true" class="demo-form-inline">
      <el-row :gutter="10" style="width: 100%;">
        <el-col :span="8">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" :disabled="isDisabled('username')" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号" :disabled="isDisabled('phone')" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" :disabled="isDisabled('email')" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button-group style="display: flex;">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-button-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格展示区域 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column prop="id" label="序号" width="80">
      <template #default="scope">
         {{ scope.$index + 1 }}
      </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="status" label="状态">
         <template #default="scope">
     <!-- 根据 status 动态显示文本和背景色 -->
          <span 
            :class="{
              'status-text': true,
              'status-enabled': scope.row.status === 1,
              'status-disabled': scope.row.status === 0
            }"
          >
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </span>
  </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          {{ formatRole(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
    {{ formatGender(scope.row.gender) }}
  </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      
      <el-table-column label="操作" width="240px">
        <template #default="scope">
          <el-button size="small" plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="success" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogFormVisible" title="编辑" width="500">
    <el-form :model="form">
      <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="手机号">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择">
          <el-option label="启用" value="启用" />
          <el-option label="禁用" value="禁用" />
        </el-select>
      </el-form-item>
      </el-col>
    </el-row>
      
      <el-row :gutter="20">
        <!-- <el-col :span="12">
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
      </el-col> -->
      <el-col :span="12">
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="保密" value="保密" />
            <el-option label="女" value="女" />
            <el-option label="男" value="男" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
      </el-col>
     </el-row>

      <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="用户名">
          <el-input v-model="form.username"  />
        </el-form-item>
      </el-col>
    </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUser" >
         保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 详情对话框 -->
<el-dialog v-model="detailDialogVisible" title="用户详情" width="50%">
  <el-form :model="detailData" label-width="120px" disabled>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="用户名">
          <el-input v-model="detailData.username" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="手机号">
          <el-input v-model="detailData.phone" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="邮箱">
          <el-input v-model="detailData.email" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态">
          <el-input v-model="detailData.status" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="角色">
          <el-input v-model="detailData.role" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="创建时间">
          <el-input v-model="detailData.createTime" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="性别">
          <el-input v-model="detailData.gender" />
        </el-form-item>
      </el-col>
    </el-row>

  </el-form>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </div>
  </template>
</el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total">
    </el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted,reactive,computed } from 'vue'
import axios from 'axios'
import{  ElMessage,ElMessageBox } from 'element-plus'
axios.defaults.baseURL = "http://localhost:8080";

// 查询表单
const searchForm = ref({
  username: '',
  phone: '',
  email: ''
})
// 是否已有输入
const hasInput = computed(() => {
  const form = searchForm.value
  if (!form) return false
  return form.username !== '' || form.phone !== '' || form.email !== ''
})

const isDisabled = (field) => {
  const form = searchForm.value
  if (!form) return false

  const { username, phone, email } = form

  switch (field) {
    case 'username':
      return hasInput.value && (phone !== '' || email !== '')
    case 'phone':
      return hasInput.value && (username !== '' || email !== '')
    case 'email':
      return hasInput.value && (username !== '' || phone !== '')
    default:
      return false
  }
}

// 所有数据
const allData = ref([])

// 当前页码 & 每页数量
const currentPage = ref(1)
const pageSize = ref(5)
// 总条数
const total = computed(() => allData.value.length)
// 分页后的表格数据
const tableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allData.value.slice(start, end)
})

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
// 选中的行
const multipleSelection = ref([])

// 获取用户列表
const getUserList = async () => {
   try {
    const token = sessionStorage.getItem('token');
    const { data } = await axios.get('/admin/list',{
    headers: {
      Authorization: `${token}` // 添加 Token 到请求头 
    }}
  );

    if (data.code === 0) {
      allData.value = data.data || [];
    } else {
      ElMessage.error(data.message || '加载失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试');
    console.error(error);
  }
}
const formatGender = (value) => {
  if (value === 1) return '女'
  if (value === 2) return '男'
  return '保密'
}
const formatStatus = (value) => {
  if (value === 1) return '启用'
  if (value === 0) return '禁用'
}
const formatRole = (value) => {
  if (value === 0) return '游客'
  if (value === 1) return '普通用户'
  if (value === 2) return '管理员'
}
//修改用户
const updateUser = async () => {
  try {
    const submitData = {
      ...form,
      status: form.status === '启用' ? 1 : 0,
      gender: form.gender === '男' ? 2 : form.gender === '女' ? 1 : 0
    };

     // 前端表单校验
    if (!submitData.username.trim()) {
      ElMessage.error('用户名不能为空');
      return;
    }

    if (!submitData.phone.trim()) {
      ElMessage.error('手机号不能为空');
      return;
    } else if (!/^1\d{10}$/.test(submitData.phone)) {
      ElMessage.error('手机号格式不正确');
      return;
    }

    if (!submitData.email.trim()) {
      ElMessage.error('邮箱不能为空');
      return;
    } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(submitData.email)) {
      ElMessage.error('邮箱格式不正确');
      return;
    }
    const token = sessionStorage.getItem('token');

    // 发送请求
    const res = await axios.post('/admin/modify', submitData,{
    headers: {
      Authorization: `${token}` // 添加 Token 到请求头 
    }}
  );
    if (res.data.code === 0) {
      ElMessage.success('修改成功');
      dialogFormVisible.value = false;
      getUserList(); // 刷新用户列表
    } else {
      ElMessage.error(res.data.message || '修改失败');
    }
  } catch (err) {
    ElMessage.error('网络错误，请稍后再试');
    console.error(err);
  }
};

// 查询
const handleSearch = async() => {
  const username = searchForm.value.username.trim();
  const phone = searchForm.value.phone.trim();
  const email = searchForm.value.email.trim();

 // 如果没有输入手机号或邮箱，直接获取所有用户信息
  if (!username && !phone && !email) {
    await getUserList();
    return;
  }

  try {
    let url = '';
    let params = {};

    if (username) {
      url = '/admin/findByName';  
      params = { username };
    } else if (phone) {
      url = '/admin/findByPhone';
      params = { phone };
    } else if (email) {
      url = '/admin/findByEmail';
      params = { email };
    }

    const token = sessionStorage.getItem('token');
    const { data } = await axios.get(url, { 
      params,
    headers: {
      Authorization: `${token}` // 添加 Token 到请求头 
    }}
    );

    if (data.code === 0) {
      allData.value = data.data || [];
      total.value = data.total || 0;
      //ElMessage.success('查询成功');
    } else {
      ElMessage.warning(data.message || '暂无数据');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试');
    console.error(error);
  }
}

// 重置
const handleReset = () => {
  searchForm.value = {
    username: '',
    phone: '',
    email: ''
  }
  getUserList()
}

const dialogFormVisible = ref(false)
const form = reactive({
  userId:'',
  username:'',
  phone: '',
  status: '',
  role: '',
  email: '',
  gender:'',
  createTime:'',
})
// 编辑
const handleEdit = (index, row) => {
  console.log('当前行数据:', row);
  form.userId = row.userId
   form.phone = row.phone;
   form.status = formatStatus(row.status);   
   form.gender = formatGender(row.gender);
   form.email = row.email;
   form.username = row.username;
   dialogFormVisible.value = true
}

const detailDialogVisible = ref(false)
const detailData = reactive({
  username:'',
  phone: '',
  status: '',
  role: '',
  email: '',
  gender:'',
  createTime: ''
})
// 详情
const handleDetail = (index, row) => {
  // 显示详情对话框
  detailData.username = row.username;
  detailData.phone = row.phone;   
  detailData.status = formatStatus(row.status); 
   detailData.role = formatRole(row.role);
   detailData.email = row.email;
   detailData.gender = formatGender(row.gender);
   detailData.createTime = row.createTime;
  detailDialogVisible.value = true
}

// 删除
const handleDelete = (index, row) => {
  // 获取当前登录用户信息
  const currentUser = JSON.parse(sessionStorage.getItem('userInfo')); 
  const currentUserId = currentUser.userId;
  const currentUserRole = currentUser.role;

  // 判断是否是删除自己，并且是超级管理员
  if (row.userId === currentUserId && currentUserRole === '3') {
    ElMessage.warning('超级管理员不能删除自己');
    return;
  }

  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const token = sessionStorage.getItem('token');
    try {
      const res = await axios.delete('/admin/delete', {
        data: { userId: row.userId },
        headers: {
          Authorization: `${token}`
        }
      });

      if (res.data.code === 0) {
        ElMessage.success('删除成功');
        getUserList(); 
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    } catch (err) {
      ElMessage.error('网络错误');
      console.error(err);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 多选改变事件
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


// 页面加载时获取用户列表
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.demo-form-inline {
  display: flex;
  align-items: center;
}
.demo-form-inline .el-button {
  border-radius: 4px; /* 修改按钮圆角 */
}
.demo-form-inline .el-button-group .el-button:not(:last-child) {
  margin-right: 15px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 状态文本基础样式 */
.status-text {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
}

/* 启用状态样式 */
.status-enabled {
  background-color: #67c23a; /* 绿色 */
}

/* 禁用状态样式 */
.status-disabled {
  background-color: #f56c6c; /* 红色 */
}
</style>